package com.dbflow5.processor.definition;

import com.dbflow5.annotation.IndexGroup;
import com.dbflow5.processor.definition.column.ColumnDefinition;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.ParameterizedTypeName;

import javax.lang.model.element.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Description:
 */
public class IndexGroupsDefinition {

    private final TableDefinition tableDefinition;

    public String indexName;
    public int indexNumber;
    public boolean isUnique;

    public List<ColumnDefinition> columnDefinitionList = new ArrayList<>();

    public IndexGroupsDefinition(TableDefinition tableDefinition, IndexGroup indexGroup) {
        this.tableDefinition = tableDefinition;
        indexName = indexGroup.name();
        indexNumber = indexGroup.number();
        isUnique = indexGroup.unique();
    }

    public FieldSpec fieldSpec() {
        CodeBlock.Builder codeBuilder = CodeBlock.builder();

        codeBuilder.add("new $T<>(\""+indexName+"\", "+isUnique+", $T.class", com.dbflow5.processor.ClassNames.INDEX_PROPERTY, tableDefinition.elementTypeName);
        if (!columnDefinitionList.isEmpty()) {
            codeBuilder.add(",");
        }
        AtomicInteger index = new AtomicInteger(0);
        columnDefinitionList.forEach(it -> it.appendIndexInitializer(codeBuilder, index));
        codeBuilder.add(")");

        FieldSpec.Builder builder = FieldSpec.builder(ParameterizedTypeName.get(com.dbflow5.processor.ClassNames.INDEX_PROPERTY, tableDefinition.elementClassName), "index_"+indexName);
        builder.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL);
        builder.initializer(codeBuilder.build());
        return builder.build();
    }

}
